/* 
 * cms，一个基于J2EE架构内容管理系统
 * Copyright © GrayRabbit Co., Ltd. All rights reserved.
 * Department:运营department
 * 更多信息请访问：
 * http://code.google.com/p/gray-rabbit-cms/
 */
package org.grayrabbit.cms.action.theme;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.grayrabbit.cms.action.common.BaseAction;
import org.grayrabbit.cms.constant.ConstantTheme;
import org.grayrabbit.cms.constant.ConstantEnum.Module;
import org.grayrabbit.cms.constant.ConstantEnum.OperAct;
import org.grayrabbit.cms.entity.Theme;
import org.grayrabbit.cms.service.theme.ThemeService;
import org.grayrabbit.cms.util.FilePathSptUtil;
import org.grayrabbit.cms.util.UploadUtil;
import org.grayrabbit.cms.vo.theme.ThemeBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;


/**
 * <b>ThemeAction</b> Struts2 action�?





 * @version 1.0,创建时间:2011-05-16 15:57:47 
 */
@Controller
@Scope("prototype")
public class ThemeAction extends BaseAction<ThemeBean> {
	private static final long serialVersionUID = -1L;
	private Logger LOG = LoggerFactory.getLogger(ThemeAction.class); 
  
	
	//Service接口接入
	@Autowired
	@Qualifier("themeServiceImpl")
	private ThemeService themeService;
 
	
	//VO对象，由前端页面数据组装
	private ThemeBean theme; 
	private String objectId;
	private File uploadFile;
	private String uploadFileFileName;
	private String themeName; 
	private List<ThemeBean> themeBeans = new ArrayList<ThemeBean>(); 
	
	/**return 前端页面数据组装VO对象,<b>ThemeBean</b>*/
	public ThemeBean getTheme() {
		return theme;
	}

	public void setTheme(ThemeBean theme) {
		this.theme = theme;
	}
	/**
	 * 在执行（struts2的action调用时）list()方法前执行本方法
	 */
	public void prepareList(){
		prepareModel();
	}
	
	/**
	 * 在执行任何其它action方法（struts2的action调用时）前执行本方法
	 */
	public void prepare(){
		if(theme==null){
			theme = new ThemeBean();
		}
	}
	/**
	 * 实现ModelDriven的接口简例前端页的bean组装写法,
	 *  如：
	 *	<pre>
	 *		<code> name="user.userName"</code>
	 *	改写成：
	 *		<code> name="userName"</code>
	 *	action实例中，会自动组成user成员变量
	 *	</pre>
	 */
	public ThemeBean getModel() {
		return theme;
	}
	
	@Override
	protected void prepareModel(){
		if(theme!= null && StringUtils.isNotBlank(theme.getThemeId())){
			theme = (ThemeBean)dozer.map(themeService.getTheme(theme.getThemeId()),ThemeBean.class);
		}
		
	}

	/**
	 * 删除<b>Theme</b>记录的方法，成员变量<b>key</b>为主键的String数组，以主键方式进行删作
	 * 删除成功后，返回"reload"，然后跳转到theme-list.action
	 */
	public String delete(){
		themeService.delete(key);
		return RELOAD;
	}
	
	/**
	 * Theme的列表方法，通过成员变量<b>page�?{insClassName}</b>调用service接口，更新page
	 * 执行成功后，将映射到theme-list.jsp页面
	 */
	@Override
	@Action(value="theme-list")
	public String list(){
		List<Theme> list = loadAllthemeinfos();
		if(list != null && !list.isEmpty()){
			ThemeBean bean = null;
			String themeRoot = getSystemThemeRoot();
			String root = FilePathSptUtil.THEME_ROOT_PATH;
			String visit = FilePathSptUtil.THEME_VISIT_URL;
			for(Theme  t:list){
				if(t!= null && StringUtils.isNotBlank(t.getThemeId())){
					bean = (ThemeBean)dozer.map(themeService.getTheme(t.getThemeId()),ThemeBean.class);	
					String path =themeRoot+FilePathSptUtil.padRightAndLeftSpt(bean.getThemeName())+ConstantTheme.THUMB_NAME;
					File  file = new File(root+path);
					if(file.exists() && file.isFile()){
						bean.setImageFlag(true);
						bean.setImagepath(visit+FilePathSptUtil.transferSpt(path));
					}else{
						bean.setImageFlag(false);
						bean.setImagepath(null);
					}
					themeBeans.add(bean);
				}
			}
		}
		return SUCCESS;
	}
	
	@Action("theme-select")
	public String themeSelect(){
		this.list();
		StringBuffer sb = new StringBuffer();
		sb.append("<option  value='-1'>请选择</option>");
		for(ThemeBean bean:themeBeans){
			if(!bean.getThemeStatus().booleanValue()  
					&& !bean.getThemeName().equalsIgnoreCase(themeName))
				continue;
			sb.append("<option value='");
			sb.append(bean.getThemeName());
			sb.append("' ");
			if(StringUtils.isNotBlank(themeName) 
					&& themeName.equalsIgnoreCase(bean.getThemeName())){
				sb.append(" selected='selected' ");
			}
			
			sb.append(">");
			sb.append(bean.getThemeName());
			sb.append("</option>");
		}		
		LOG.info("\n\n"+sb.toString());
		return renderHtml(sb.toString());
	}
	
	/**
	 * Theme的新增与编辑的方法执行成功能
	 * 将映射到theme-input.jsp
	 */
	public String input(){
		prepareModel();
		return SUCCESS;
	}
	
	/**
	 * save or update Theme的方法，将成员property theme转成Theme实例，执行保存；
	 * 执行成功后，返回"reload"，然后跳转到theme-list.action
	 */
	@Override
	public String save(){
		Theme obj = (Theme) dozer.map(theme, Theme.class);
		if(!StringUtils.isNotBlank(obj.getThemeId())){
			obj.setThemeId(null);
		}
		themeService.save(obj);
		return RELOAD;
	}
	/**
	 * @return
	 */
	public  List<Theme> loadAllthemeinfos(){
		String root = FilePathSptUtil.THEME_ROOT_PATH;
		List<Theme> list = themeService.findAllRealUsableTheme(root+getSystemThemeRoot()); 
		return list;
	}
	
	/**系统主题根路径 相对路径
	 * @return
	 */
	private String getSystemThemeRoot(){
		return ConstantTheme.THEME;
	}
	
	@Action(value="theme-change")
    public String enabledChange(){
    	String text = null;
		if(StringUtils.isBlank(objectId)) {
			text="{flag:false,msg:'请要选择操作的对象'}"; 
		}else { 
			boolean f = themeService.findSiteByTheme(objectId);
			if(f){
				return renderText("{flag:false,msg:'该主题已经被引用不能禁止'}");
			}		
			boolean flag  = themeService.changeThemeStatus(objectId);
			String act =null;
			if(flag){
				// 当前状态变成启用，图片css变亮，按钮显‘示禁用’
				text ="{flag:true,msg:'操作成功',show:false}";
				act = OperAct.ENABLE.getValue();
			}else{
				// 当前状态变成禁用，图片css变灰，按钮显‘示启用’
				text ="{flag:true,msg:'操作成功',show:true}";
				act = OperAct.DISABLE.getValue();
			}
			addLog(Module.THEME.getValue(), act, objectId);
		} 	
		LOG.info(text);
    	return renderText(text);
    } 
	
	/**
	 * @return
	 */
	@Action(value="theme-upload")
	public String upload(){
		if(uploadFile == null){
			return renderText("{flag:false,msg:'请选择上传文件'}");
		}
		int index = uploadFileFileName.lastIndexOf('.');
		if(index == -1)
			return renderText("{flag:false,msg:'文件没有后缀名不能上传'}");
		String fix = uploadFileFileName.substring(index+1);
		if(!fix.equalsIgnoreCase("zip")) 
			return renderText("{flag:false,msg:'本功能只支持ZIP文件上传'}");
		String fileName = uploadFileFileName.substring(0, index);
		if(StringUtils.isBlank(fileName))
			return renderText("{flag:false,msg:'文件没有文件名不能上传'}");
		try {
			String root = FilePathSptUtil.THEME_ROOT_PATH;
			fileName = root+getSystemThemeRoot()+FilePathSptUtil.padLeftSpt(uploadFileFileName);
			File file = new File(fileName);	
			deleteExitsFile(file);
			FileUtils.copyFile(uploadFile, file);
			
			UploadUtil.releaseZipToFile(fileName, file.getParentFile().getAbsolutePath());
			deleteExitsFile(file);
		} catch (IOException e) {
			LOG.error("上传异常", e);
			e.printStackTrace();
			return renderText("{flag:false,msg:'上传/解压异常'}");
		}
	 			
		return renderText("{flag:true,msg:'主题上传/解压成功'}");
	}
	 
	private  void deleteExitsFile(File file) {
		if(file.exists() && file.isFile()){
			file.delete();
		}
	}

	public List<ThemeBean> getThemeBeans() {
		return themeBeans;
	}

	public void setThemeBeans(List<ThemeBean> themeBeans) {
		this.themeBeans = themeBeans;
	}
 
	public File getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}

	public String getUploadFileFileName() {
		return uploadFileFileName;
	}

	public void setUploadFileFileName(String uploadFileFileName) {
		this.uploadFileFileName = uploadFileFileName;
	}

	public String getThemeName() {
		return themeName;
	}

	public void setThemeName(String themeName) {
		this.themeName = themeName;
	}

	public String getObjectId() {
		return objectId;
	}

	public void setObjectId(String objectId) {
		this.objectId = objectId;
	}
	 
}